import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:logging/logging.dart';
import 'package:freesic/model/user_detail_bean.dart';
import 'package:netease_music_api/netease_music_api.dart';

final userProvider =
    StateNotifierProvider<UserAccount, UserDetail?>((ref) => UserAccount());

final isLoginProvider = Provider<bool>((ref) {
  return ref.watch(userProvider) != null;
});

final userIdProvider = Provider.autoDispose<int?>((ref) {
  return ref.watch(userProvider)?.userId;
});

extension UserDetailExt on UserDetail? {
  UserDetail? get userDetail => this;

  UserProfile get profile => userDetail!.profile;

  ///当前是否已登录
  bool get isLogin {
    return this != null;
  }

  ///当前登录用户的id
  ///null if not login
  int? get userId {
    if (!isLogin) {
      return null;
    }
    return profile.userId;
  }
}

/// 登录状态
/// TODO

class UserAccount extends StateNotifier<UserDetail?> {
  UserAccount() : super(null);

  final logger = Logger("UserAccount");

  static const _persistenceKey = 'neteaseLoginUser';

  Future<void> login(String? phone, String password) async {
    final result = await NeteaseMusicApi().loginCellPhone(phone!, password);
    // if (result.isValue) {
    // final json = result.asValue!.value;
    final userId = result.account!.id;

    final userDetailResult =
        await NeteaseMusicApi().userDetail(userId.toString());
    if (userDetailResult.codeEnum != RetCode.Ok) {
      final error = userDetailResult;
      debugPrint('error : ${error.message}');
      // return Result.error("can not get user detail.");
    }
    // }
    // return result;
  }

  void logout() {
    NeteaseMusicApi().logout();
  }

  UserDetail? get userDetail => state;

  UserProfile get profile => userDetail!.profile;

  ///当前是否已登录
  bool get isLogin {
    return NeteaseMusicApi().usc.isLogined;
  }

  ///当前登录用户的id
  ///null if not login
  int? get userId {
    if (!isLogin) {
      return null;
    }
    return state!.profile.userId;
  }
}
